package com.rocksdata.mc.ui.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.ctz.commonframe.ui.TitleBarActivity;
import com.ctz.commonframe.utils.ApplicationUtil;
import com.ctz.commonframe.utils.GlideAppUtil;
import com.ctz.commonframe.utils.Logger;
import com.ctz.commonframe.utils.SharedPrefrencesUtil;
import com.rocksdata.mc.MobileCampusApplication;
import com.rocksdata.mc.R;
import com.rocksdata.mc.SharedPreferencesKey;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.business.UserInfoManager;
import com.rocksdata.mc.business.VersionManager;
import com.rocksdata.mc.entity.VersionInfo;
import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import java.io.File;

/**
 * Created by 陈堂正 on 2017/4/6.
 */
@ContentView(R.layout.activity_settings)
public class SettingsActivity extends TitleBarActivity {
    @ViewInject(R.id.tv_cache_size)
    private TextView tvCacheSize;
    @ViewInject(R.id.tv_version)
    private TextView tvVersion;
    @ViewInject(R.id.iv_version_flag)
    private ImageView ivVersionFlag;

    private ProgressDialog pbDownloading;
    private boolean isNeedUpdate;
    private VersionInfo versionInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleMiddleText("通用设置");
        GlideAppUtil.getDiskCacheSize(tvCacheSize);
        versionInfo = VersionManager.getVersionInfo();
        tvVersion.setText(ApplicationUtil.getAppVersion(this));
        isNeedUpdate = VersionManager.isLatestVersion(this, versionInfo);
        ivVersionFlag.setVisibility(isNeedUpdate ? View.VISIBLE : View.GONE);
    }

    @Event(value = {R.id.layout_help, R.id.layout_other_platform, R.id.layout_clear_cache, R.id.layout_check_version, R.id.layout_about, R.id.layout_privacy, R.id.layout_modify_password})
    private void OnClick(View v) {
        switch (v.getId()){
            case R.id.layout_help:
                break;
            case R.id.layout_other_platform:
                startActivity(new Intent(SettingsActivity.this, OtherPlatformActivity.class));
                break;
            case R.id.layout_clear_cache:
                GlideAppUtil.clearMemoryCache(MobileCampusApplication.getContext());
                GlideAppUtil.clearDiskCache(MobileCampusApplication.getContext());
                tvCacheSize.setText("0 B");
                break;
            case R.id.layout_check_version:
                showVersionDialog(isNeedUpdate);
                break;
            case R.id.layout_about:
                startActivity(new Intent(SettingsActivity.this, AboutActivity.class));
                break;
            case R.id.layout_privacy:
                String pwd = (String) SharedPrefrencesUtil.getAboutUser(UserInfoManager.getCurrentUserId(), SharedPreferencesKey.KEY_GESTURE_PASSWORD, "");
                boolean hasPassword = !TextUtils.isEmpty(pwd);
                if(hasPassword)
                    startActivity(new Intent(SettingsActivity.this, GesturePasswordUnlockActivity.class)
                            .putExtra("className", "com.rocksdata.mip.ui.activity.PrivacySettingsActivity"));
                else
                    startActivity(new Intent(SettingsActivity.this, GesturePasswordGuideActivity.class));
                break;
            case R.id.layout_modify_password:
                startActivity(new Intent(SettingsActivity.this, ModifyPasswordActivity.class));
                break;
        }
    }

    private void showVersionDialog(boolean isNeedUpdate) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("检查版本");
        builder.setMessage(isNeedUpdate ? "最新版本是" + versionInfo.getVersionName() + ",是否更新" : "当前已经是最新版本");
        builder.setNegativeButton(isNeedUpdate ? "暂不更新" : "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        if (isNeedUpdate) {
            builder.setPositiveButton("马上更新", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    update();
                }
            });
        }
        builder.show();
    }


    private void update() {
        if(pbDownloading == null){
            pbDownloading = new ProgressDialog(SettingsActivity.this);
            pbDownloading.setCanceledOnTouchOutside(false);
            pbDownloading.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pbDownloading.setProgressNumberFormat("%1d MB /%2d MB");
        }
        BusinessManager.getVersionManager().updateVersion(SettingsActivity.this, versionInfo, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {
                pbDownloading.setTitle("正在下载");
                pbDownloading.setMessage("请稍候...");
                pbDownloading.show();
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                pbDownloading.setMax((int) (total/(1024*1024)));
                pbDownloading.setProgress((int) (current/(1024*1024)));
            }

            @Override
            public void onSuccess(File file) {
                Logger.e("download success, path:" + file.getAbsolutePath());
                pbDownloading.dismiss();
                ApplicationUtil.installApk(SettingsActivity.this, file.getAbsolutePath());
                exit();
                android.os.Process.killProcess(android.os.Process.myPid());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pbDownloading.dismiss();
                showToast("下载失败");
                Logger.e("下载失败，url:" + versionInfo.getVersionURL() + ", msg:" + ex.getLocalizedMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                pbDownloading.dismiss();
            }

            @Override
            public void onFinished() {
                pbDownloading.dismiss();
            }
        });
    }
}
